import { getFullURL } from '@/utils/http'
interface FIleItem {
  /** 图片 id */
  id: string
  /** oss 地址 */
  url: string
  /** 图片名称 */
  name?: string
  size?: number
  thumb?: string
  status?: string
  message?: string
}
const baseURL = import.meta.env.VITE_BASE_API_URL
const _request = (config) => {
  const { url, method, data, params, headers = {}, paramsSerializer } = config
  const gateUrl = config.baseURL ? config.baseURL : baseURL
  const token = uni.getStorageSync('token')
  // 附带鉴权的token
  Object.assign(headers, {
    Authorization: 'Bearer ' + token
  })
  return new Promise((resolve, reject) => {
    uni.showLoading({
      title: '加载中...'
    })
    uni.request({
      method: method!.toUpperCase() as any,
      url: getFullURL(gateUrl || '', url!, params, paramsSerializer),
      header: headers,
      data,
      dataType: 'json',
      responseType: config.responseType,
      success: (res: any) => {
        uni.hideLoading()
        if (!res?.data?.code) {
          resolve(res)
        } else {
          if (res.data.code === 1000) {
            uni.showToast({
              title: "令牌错误（无效），请重新登录",
              icon: "error",
            })
            uni.navigateTo({
              url: '/pages/login/index'
            })
          } else if (res.data.code === 1001) {
            uni.showToast({
              title: "令牌过期（失效），请重新登录",
              icon: "error",
            })
            uni.navigateTo({
              url: '/pages/login/index'
            })
          } else if (res.data.code === 1003) {
            uni.showToast({
              title: "请修改密码",
              icon: "error",
            })
            uni.setStorageSync('token', res.data.data.token)
            uni.navigateTo({
              url: '/pages/updatePassword/index?gotopage=index'
            })
          } else if (res.data.code === 1004) {
            uni.showToast({
              title: "首次登录，请修改密码",
              icon: "error",
            })
            uni.setStorageSync('token', res.data.data.token)
            uni.navigateTo({
              url: '/pages/updatePassword/index?first=1'
            })
          } else if (res.data.code === 200 || res.data.code === 1002) {
            resolve(res)
          } else {
            errorHandling(res.data)
          }

        }
      },
      fail: (err: any) => {
        uni.hideLoading()
        uni.showToast({
          title: "请求失败，请稍后再试",
          icon: "error",
        })
        reject(err)
      }
    })
  })
}


// 统一错误处理
function errorHandling(res) {
  const err = {
    message: res.msg,
    code: res.code,
  }
  uni.showToast({
    title: err.message,
    icon: "error",
  })
  return Promise.reject({
    ...err,
  })
}

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url: string, params = {}, config = {}) {
  return _request({
    url: url,
    method: "GET",
    data: params,
    ...config
  })
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url: string, params = {}, config = {}) {
  return _request({
    url: url,
    method: "POST",
    data: params,
    ...config
  })
}

/*
 *  delete请求
 *  url:请求地址
 *  params:参数
 * */
export function del(url: string, params = {}, config = {}) {
  return _request({
    url: url,
    method: "DELETE",
    data: params,
    ...config
  })
}

// 上传、下载文件
export function uploadFilePromise(config: any): Promise<any> {
  const { fileUrl, url, params, headers = {}, paramsSerializer } = config
  // 附带鉴权的token
  Object.assign(headers, {
    Authorization: 'Bearer ' + uni.getStorageSync('token')
  })

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: getFullURL(baseURL || '', url!, params, paramsSerializer),
      filePath: fileUrl,
      name: 'files',
      formData: config.data || undefined,
      header: headers,
      success: (res) => {
        if (res?.statusCode === 200) {
          try {
            const parseData = JSON.parse(res?.data)
            resolve(parseData)
          } catch (error) {
            resolve({ error: true })
          }
        } else {
          resolve({ error: true })
        }
      },
      fail: (err) => {
        resolve({ error: true })
      },
    })
  })
}

export function checkSize(size: number) {
  const _size = size / 1024 / 1024 // 单位 M
  const max = 10
  if (_size > max) {
    uni.showToast({ title: `文件大小不能超过${max}M`, icon: 'none' })
    return false
  } else {
    return true
  }
}
// 暂存图片信息
export function handleFile(event: any) {
  console.log("🚀 ~ handleFile ~ event:", event)
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  const photos: any[] = []
  let lists = [].concat(event.file || [])
  lists.forEach((item: FIleItem) => {
    photos.push({
      ...item,
      status: checkSize(item.size!) ? 'success' : 'failed',
      message: checkSize(item.size!) ? '' : '文件过大',
    })
  })
  return photos
}
/** 图片上传，发送给服务器 */
export async function uploadFile(photos: any[], apiUrl: string, data?: any, itemCallBack?: (index: number, item: any, newItem: any) => void, callback?: (val?: any) => void, params?: any) {
  photos.forEach(async (item: any, index: number) => {
    if (item.status === 'success' && !item.isUploading || item.id) {
      item.isUploading = true // 标记已经在上传了，避免重复上传
      const config = {
        fileUrl: photos[index].url,
        url: apiUrl,
        data: data || undefined,
      }
      const res = await uploadFilePromise(config)
      const { msg, success } = res
      const newItem = success
        ? {
          status: 'success',
          message: '',
        }
        : {
          status: 'success',
          message: '',
        }
      // photos.splice(index, 1, Object.assign(item, newItem))
      itemCallBack && itemCallBack(index, item, newItem)
    }
  })
  callback && callback(params)
}

export default {
  get,
  post,
  del,
  delete: del,
  uploadFile,
  handleFile,
  uploadFilePromise,
  checkSize,
}
